/*
 * @Author: 我想吃余 483766615@qq.com
 * @Date: 2025-11-12 20:13:52
 * @LastEditors: 我想吃余 483766615@qq.com
 * @LastEditTime: 2025-11-13 01:04:25
 * @FilePath: /code/oscode/cp/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include <iostream>
#include <unistd.h>
#include <ctime>
#include "block_queue.hpp"
#include "task.hpp"

using namespace std;

void* Produce(void* arg)
{
    block_queue<Task> *bq = (block_queue<Task>*) arg;
    while(true)
    {
        //模拟获取一个任务
        int x = rand()%10 + 1;
        usleep(13);
        int y = rand()%10;
        char op = opers[rand()%5];
        Task task(x, y, op);
        //生产任务
        bq->push(task);
        cout << "Thread id:" << pthread_self() << " 生产了一个任务: " << task.GetTask() << endl;
        usleep(10000);
    }
}

void* Consume(void* arg)
{
    block_queue<Task> *bq = (block_queue<Task>*) arg;
    while(true)
    {
        //消费
        Task task = bq->pop();
        task();
        cout << "Thread id:" << pthread_self() << "处理了一个任务: " << task.GetResult() << endl;
    }
}

int main()
{
    srand(time(nullptr)/3);//随机数种子
    block_queue<Task> *bq = new block_queue<Task>();
    pthread_t ptid[3], ctid[5];

    for(int i = 0; i < 3; ++i)
    {
        pthread_create(ptid+i, nullptr, Produce, (void*)bq);
    }

    for(int i = 0; i < 5; ++i)
    {
        pthread_create(ctid+i, nullptr, Consume, (void*)bq);
    }
 

    for(int i = 0; i < 3; ++i)
    {
        pthread_join(ptid[i], nullptr);
    }

    for(int i = 0; i < 5; ++i)
    {
        pthread_join(ctid[i], nullptr);
    }
    delete bq;
    return 0;
}